<template>
  <div class="exam-container">
    <!-- 左侧答题卡 -->
    <el-row :gutter="20" style="height: 100%">
      <el-col :span="6" class="col-class">
        <div class="answer-sheet">
          <div class="answer-sheet-header">
            <h3>答题卡</h3>
            <!-- 状态提示 -->
            <div class="status-legend">
              <div class="legend-item">
                <span class="status-indicator unanswered"></span> 未答题
              </div>
              <div class="legend-item">
                <span class="status-indicator answered"></span> 已答题
              </div>
            </div>
          </div>
          <div class="answer-sheet-content">
            <div v-for="(group, groupIndex) in groupedQuestions" :key="groupIndex" class="question-group">
              <div class="group-title">{{ group.title }}</div>
              <div class="group-buttons">
                <div
                    v-for="(item, index) in group.questions"
                    :key="index"
                    class="question-button-wrap"
                    @click="jumpToQuestion(item.index)"
                >
                  <div :class="['status-indicator', item.answered ? 'answered' : 'unanswered']"></div>
                  <el-button
                      :class="['answer-sheet-item', { answered: item.answered }]"
                  >
                    {{ item.index + 1 }}
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-col>

      <!-- 右侧答题区 -->
      <el-col :span="18" class="col-class">
        <div class="right-area">
          <!-- 考试基本信息 -->
          <div class="exam-info">
            <div class="info-item">
              <strong>考试名称：</strong>{{ examName }}
            </div>
            <div class="info-item">
              <strong>倒计时：</strong>{{ countdown }}
            </div>
          </div>

          <!-- 答题区域 -->
          <div class="question-area">
            <div class="question-header">
              <h3>题目 {{ currentQuestionIndex + 1 }} / {{ questionList.length }}</h3>
            </div>
            <div class="question-content">
              <div class="question-title">题目：</div>
              <div v-html="currentQuestionValue.content"></div>
              <!-- 根据题型区分 -->
              <template v-if="currentQuestionValue.type === 'single'">
                <div class="question-options-title">选项：</div>
                <el-radio-group v-model="currentQuestionValue.userAnswer">
                  <el-radio
                      v-for="(option, optionIndex) in currentQuestionValue.options"
                      :key="optionIndex"
                      :label="option.key"
                      class="question-option"
                  >
                    <span>{{ option.key }}. </span>
                    <span v-html="option.value"></span>
                  </el-radio>
                </el-radio-group>
              </template>

              <template v-else-if="currentQuestionValue.type === 'multiple'">
                <div class="question-options-title">选项：</div>
                <el-checkbox-group v-model="currentQuestionValue.userAnswer">
                  <el-checkbox
                      v-for="(option, optionIndex) in currentQuestionValue.options"
                      :key="option.key"
                      :label="option.key"
                      class="question-option"
                  >
                    <span>{{ option.key }}. </span>
                    <span v-html="option.value"></span>
                  </el-checkbox>
                </el-checkbox-group>
              </template>

              <template v-else-if="currentQuestionValue.type === 'judgment'">
                <div class="question-options-title">请选择：</div>
                <el-radio-group v-model="currentQuestionValue.userAnswer">
                  <el-radio label="A">正确</el-radio>
                  <el-radio label="B">错误</el-radio>
                </el-radio-group>
              </template>

              <template v-else-if="currentQuestionValue.type === 'fill'">
                <div class="question-options-title">请填写答案：</div>
                <el-input type="textarea" v-model="currentQuestionValue.userAnswer"></el-input>
              </template>

              <template v-else-if="currentQuestionValue.type === 'essay'">
                <div class="question-options-title">请简答：</div>
                <rich-text-editor v-model:get-html="currentQuestionValue.userAnswer" height="200px"/>
<!--                <el-input type="textarea" v-model="currentQuestionValue.userAnswer"></el-input>-->
              </template>
            </div>
          </div>
          <div v-if="currentQuestion"></div>
          <!-- 操作区域 -->
          <div class="operation-area">
            <el-button @click="prevQuestion" :disabled="currentQuestionIndex === 0">上一题</el-button>
            <el-button @click="nextQuestion" :disabled="currentQuestionIndex === questionList.length - 1">下一题</el-button>
            <el-button @click="saveAnswer">保存答案</el-button>
            <el-button type="primary" @click="submitExam">提交试卷</el-button>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import {ref, computed, onMounted, onBeforeUnmount, toRefs, defineEmits} from 'vue';
import {
  addExamUserApi,
  checkSubmit,
  getCurrentExamQuestion,
  getExamQuestionId,
  saveExamAnswer, submit
} from "@/api/question/exam.js";
import RichTextEditor from "@/components/RichTextEditor.vue";
import {ElMessage, ElMessageBox} from "element-plus";

// 数据部分
const countdown = ref(""); // 倒计时
const currentQuestionValue=ref({})
const questionList = ref([
]);
const props = defineProps({
  //子组件接收父组件传递过来的值
  examId: 0,
  endTime:'',
  examName:''
})

const {examId,endTime,examName} =toRefs(props)
const currentQuestionIndex = ref(0);
let timer = null;
const emit = defineEmits(['close'])
// 计算属性
const currentQuestion = computed(async  () => {
  //获取当前的题目
  await getQuestion()
});

const getQuestion=async () => {
 let questionId=null
  questionId = questionList.value[currentQuestionIndex.value]==null?-1:questionList.value[currentQuestionIndex.value].questionId
  if (questionId != null&&questionId!==-1) {
    const res = await getCurrentExamQuestion(examId.value, questionId)
    currentQuestionValue.value = res.data
    if (res.data.type==='multiple'){
      //拆分data
      currentQuestionValue.value.userAnswer= res.data.userAnswer ? res.data.userAnswer.split(",") : []
    }else {
      if(res.data.userAnswer==null){
        currentQuestionValue.value.userAnswer=''
      }
    }
  }
}
const groupedQuestions = computed(() => {
  const groups = {};
  questionList.value.forEach((question, index) => {
    if (!groups[question.type]) {
      groups[question.type] = { title: getGroupTitle(question.type), questions: [] };
    }
    groups[question.type].questions.push({ ...question, index });
  });
  return Object.values(groups);
});

// 方法
function getGroupTitle(type) {
  switch (type) {
    case 'single':
      return '选择题';
    case 'multiple':
      return '多选题';
    case 'judgment':
      return '判断题';
    case 'fill':
      return '填空题';
    case 'essay':
      return '简答题';
    default:
      return '未知题型';
  }
}

async function jumpToQuestion(index) {
  await saveResult()
  currentQuestionIndex.value = index;
  await getQuestion()
}

async function prevQuestion() {
  if (currentQuestionIndex.value > 0) {
    await saveResult()
    currentQuestionIndex.value--;
    await getQuestion()
  }
}

async function nextQuestion() {
  if (currentQuestionIndex.value < questionList.value.length - 1) {
    await saveResult()
    currentQuestionIndex.value++;
    await getQuestion()
  }
}

async function submitExam() {
 const res= await checkSubmit(examId.value)
  const message=ref("提交试卷后不可作答，确定提交？")
  if (!res.data){
    message.value="您还有未作答题目，提交试卷后不可作答，确定提交？"
  }
  ElMessageBox.confirm(message.value, '确认提交', {
    app: undefined, components: undefined, config: undefined, directives: undefined, mixins: [], provides: undefined,
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res=await submit(examId.value)
    if (res.data){
      ElMessage.success("提交试卷成功")
      emit("close")
    }
  }).catch(()=>{})
}

function updateCountdown() {
  const now = new Date();
  const end = new Date(endTime.value);
  const diff = Math.max(0, end - now);

  const hours = Math.floor(diff / (1000 * 60 * 60));
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((diff % (1000 * 60)) / 1000);

  countdown.value = `${hours}小时 ${minutes}分钟 ${seconds}秒`;

  if (diff === 0) {
    clearInterval(timer);
    alert("考试时间已到，自动提交试卷！");
    submitExam();
  }
}

// 生命周期钩子
onMounted(() => {
  initExamQuestionIds(examId.value)
  updateCountdown();
  timer = setInterval(updateCountdown, 1000);
});

onBeforeUnmount(() => {
  clearInterval(timer);
});
const initExamQuestionIds=async (examId) => {
  //初始化题目id
  const res=await getExamQuestionId(examId)
  questionList.value=res.data
}

const saveAnswer=()=>{
  saveResult()
}
//存储答案
const saveResult=async ()=>{
  const  questionId= questionList.value[currentQuestionIndex.value].questionId
  const userAnswer=currentQuestionValue.value.userAnswer
  console.log(userAnswer)
  if (userAnswer!=null&&userAnswer!==''&&userAnswer.length!==0&&userAnswer!=='<p><br></p>'){
    const data={
      examId:examId.value,
      examQuestionId:questionId,
      userAnswer:userAnswer,
      questionType:currentQuestionValue.value.type
    }
    const res= await saveExamAnswer(data)
    if (res.data){

      questionList.value[currentQuestionIndex.value].answered=true
    }
  }

}
</script>

<style scoped>
.exam-container {
  width: 100%;
  height: 100%;
  font-family: 'Helvetica Neue', Arial, sans-serif;
}

.col-class {
  height: 100%;
}

/* 答题卡区域 */
.answer-sheet {
  height: 792px;
  overflow-y: auto;
  padding: 20px;
  border-radius: 16px;
  background-color: #ffffff;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.answer-sheet-header {
  text-align: center;
  font-size: 20px;
  color: #333;
  margin-bottom: 20px;
}

.status-legend {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
}

.legend-item {
  display: flex;
  align-items: center;
}

.status-indicator {
  width: 15px;
  height: 15px;
  border-radius: 50%;
  margin-right: 5px;
}

.unanswered {
  background-color: #eaeaea; /* 未答题的颜色 */
}

.answered {
  background-color: #67c23a; /* 已答题的颜色 */
}

.question-group {
  margin-bottom: 20px;
}

.group-title {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 10px;
}

.group-buttons {
  display: grid;
  grid-template-columns: repeat(6, minmax(45px, 1fr));
  gap: 20px;
}

.question-button-wrap {
  display: flex;
  align-items: center;

}

.answer-sheet-item {
  padding: 10px;
  border: none;
  width: 40px;
  height: 40px;
  background-color: #eaeaea;
  color: #333;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 8px;
}

.answer-sheet-item:hover {
  background-color: #dcdcdc;
}

.answer-sheet-item.answered {
  background-color: #67c23a;
  color: white;
}

/* 右侧答题区 */
.right-area {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.exam-info {
  padding: 20px;
  background-color: #ffffff;
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.info-item {
  margin-bottom: 10px;
  font-size: 16px;
}

.question-area {
  overflow-y: auto;
  height: 570px;
  padding: 20px;
  border-radius: 16px;
  background-color: #ffffff;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.question-header {
  text-align: center;
  font-size: 20px;
  color: #333;
  margin-bottom: 20px;
}

.question-content {
  padding: 20px;
}

.question-title {
  font-weight: bold;
  font-size: 18px;
  color: #333;
  margin-bottom: 15px;
}

.question-options-title {
  font-weight: bold;
  font-size: 16px;
  color: #333;
  margin-bottom: 10px;
}

.option-group {
  margin-top: 10px;
}

.question-option {
  display: block;
  margin-bottom: 10px;
  font-size: 14px;
}

.fillin-answer, .short-answer {
  width: 100%;
  margin-top: 10px;
}

.operation-area {
  padding: 20px;
  background-color: #ffffff;
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  text-align: right;
}

.el-button {
  padding: 10px 20px;
  font-size: 14px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.el-button--primary:hover {
  background-color: #66b1ff;
}
</style>